# -*- coding: ISO-8859-1 -*-
# Exibe os resultados do calculo 
# utiliza as classes: 
# 1. frmconcentra: formulario criado pelo QtDesigner 
# 2. VispectFuncs: Funções para manipular o formulario acima para inclusão dos dados na tabela.
# 3. frmResConcentra: 

from PyQt4 import QtGui, QtCore
from frmResultado import Ui_frmvispect
 
import sys, string
from os.path import isfile
from os import chdir

import os
 
import frmconcentra
import crtFuncoes
import frmResConcentra 
 
## Create a dictionary of updateable variables. These will be updated by the various
## functions of Class startGui
 
## the Ui_tstMain module is imported and is a file generated by pyuic4, out of
## a "layout" file tstMain.ui created by Qt4
class startGui(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_frmvispect()
        self.ui.setupUi(self)
        self.nlinhas= None
        ## create our slots here
#        self.ui.lblespectro.setText('aaaaaa')
        QtCore.QObject.connect(self.ui.cmdimprimir, QtCore.SIGNAL("clicked()"), self.imprimir)
        QtCore.QObject.connect(self.ui.cmdconcentra, QtCore.SIGNAL("clicked()"), self.fconcentra)
        QtCore.QObject.connect(self.ui.cmdteste, QtCore.SIGNAL("clicked()"), self.calcular)
        QtCore.QObject.connect(self.ui.cmdGravar, QtCore.SIGNAL("clicked()"), self.guarda)
        QtCore.QObject.connect(self.ui.cmdgracon, QtCore.SIGNAL("clicked()"), self.gravaResultados)
#        QtCore.QObject.connect(self.ui.cmdgracon, QtCore.SIGNAL("clicked()"), self.gravaConcentracao)
#        QtCore.QObject.connect(self.ui.cmdlercon, QtCore.SIGNAL("clicked()"), self.muda)
        QtCore.QObject.connect(self.ui.cmdlercon, QtCore.SIGNAL("clicked()"), self.lerResultados)
 
    def lerResultados(self):
# teste gravando tabela de elementos para busca
        arq='cp-1a.res'
        f=open(arq,'r')
        linha = f.readline()
        vinfo={}
        vgdic={}
        i=0
        while (len(linha)):
            if linha[0] == '#':
               vinfo[string.split(linha,',')[0][1:]]=string.split(linha,',')[1][:-1]
            else:
               r=string.split(linha,',')
               vdic={}
               vdic['energia']=r[0]
               vdic['area']=r[1]
               vdic['bg']=r[2]
               vdic['resol']=r[3]
               vdic['fi']=r[4]
               vdic['id']=r[5]
               vdic['lp']=r[6]
               vdic['cps']=r[7]
               vdic['erreur']=r[8]
               vdic['elem']=r[9]
               vdic['meiavida']=r[10]
               vdic['massa']=r[11]
               vgdic[i]=vdic
               i=i+1
            linha = f.readline()
        f.close()
#        print vgdic
#        print vinfo
        file=0       

    def gravaResultados(self):
# teste gravando tabela de elementos para busca
        arq='c:'+self.ui.lblespectro.text()[3:-4]+'.res'
        f=open(arq,'w')
        f.write('#SourceName,'+self.ui.lblespectro.text() + "\n")
        f.write('#TempoVivo,'+self.ui.lblvivo.text() + "\n")
        f.write('#TempoTotal,'+self.ui.lblmorto.text() + "\n")
        f.write('#Data,'+self.ui.txtdata.text() + "\n")
        f.write('#Hora,'+self.ui.txthora.text() + "\n")
        n=self.nlinhas
        for fila in range(n):
            texto = self.ui.tableWidget.item(fila,0).text()
            for i in range(1,12):
                if i == 9:
                   texto = texto + ",'" + self.ui.tableWidget.item(fila,i).text()+ "'" 
                else:
                   texto = texto + "," + self.ui.tableWidget.item(fila,i).text() 
            texto = texto + "\n"
            f.write(texto)
        f.close()
        file=0       

    def muda(self):
#       print 'iiiiiiiiiiiiiiiiiiiiiii'
        print type(self.ui.lblespectro.text())
        self.ui.lblespectro.setText('xxxxxxxx')
                
    def imprimir(self):
#       print 'iiiiiiiiiiiiiiiiiiiiiii'
        msg = QtGui.QMessageBox(self)
        msg.setIcon(QtGui.QMessageBox.Critical)
        msg.setText("Erro: Impressão Indisponível!")
        msg.exec_()
        return


    def calcular(self):
# rotina de exemplo abre nova janela 
        n=self.nlinhas
        dconcentra = QtGui.QDialog()
        ui = frmResConcentra.Ui_fResConcentra()
        ui.setupUi(dconcentra)
        linha=0
        ui.tableWidget.setRowCount(linha+1)
        ui.tableWidget.setColumnCount(7)            
        for fila in range(n):
            if self.ui.tableWidget.item(fila,9).text() == 'X':
               valor=QtGui.QTableWidgetItem(self.ui.tableWidget.item(fila,0).text(), QtGui.QTableWidgetItem.Type)
               ui.tableWidget.setItem(linha,0,valor)
               valor=QtGui.QTableWidgetItem(self.ui.tableWidget.item(fila,1).text(), QtGui.QTableWidgetItem.Type)
               ui.tableWidget.setItem(linha,1,valor)
               valor=QtGui.QTableWidgetItem(self.ui.tableWidget.item(fila,2).text(), QtGui.QTableWidgetItem.Type)
               ui.tableWidget.setItem(linha,2,valor)
               valor=QtGui.QTableWidgetItem(self.ui.tableWidget.item(fila,3).text(), QtGui.QTableWidgetItem.Type)
               ui.tableWidget.setItem(linha,3,valor)
               valor=QtGui.QTableWidgetItem(self.ui.tableWidget.item(fila,4).text(), QtGui.QTableWidgetItem.Type)
               ui.tableWidget.setItem(linha,4,valor)
               valor=QtGui.QTableWidgetItem(self.ui.tableWidget.item(fila,5).text(), QtGui.QTableWidgetItem.Type)
               ui.tableWidget.setItem(linha,5,valor)
               vr=int(self.ui.tableWidget.item(fila,6).text())+1
               valor=QtGui.QTableWidgetItem("%8d" % vr, QtGui.QTableWidgetItem.Type)
               ui.tableWidget.setItem(linha,6,valor)
               linha=linha+1
               ui.tableWidget.setRowCount(linha+1)
        ret=dconcentra.exec_()

    def guarda(self):
# rotina de exemplo salvar dados em um arquivo 
        fileName = QtGui.QFileDialog.getSaveFileName(self,
             self.tr("Guardar archivo"),
             "C:\\Python24\\Lib\\site-packages\\pydanirc\\datos\\",
             self.tr("All Files (*);;Text Files (*.txt)"))
        if not fileName.isEmpty():
           t = fileName
           f=open(str(t),'w+')
           for fila in range(10):
               if self.ui.tableWidget.item(fila,0).text() == 'X':
                  texto = self.ui.tableWidget.item(fila,0).text() + ";" +self.ui.tableWidget.item(fila,1).text()+"\r\n"
                  f.write(texto)
           f.write('passou')
           f.close()

    def fconcentra(self):
#exibe tela para entrada de dados para calculo da concentração, antes verificar se está marcado....algum item para o calculo 
        dconcentra = QtGui.QDialog()
        ui = frmconcentra.Ui_dconcentra()
        ui.setupUi(dconcentra)
        ret=dconcentra.exec_()
# se ret for 1 apertou ok se 0 cancela.......        
        if ret:
            vdic={}
            v=str(ui.txt1.text())
            #print initialFile['txt1']
            vdic['txt1'] = v
            vdic['txt2'] = str(ui.txt2.text())
            file=open("c:concentra.txt",'w')
#            file.write("%s  %s\n" %(ui.txt1.text(),ui.txt2.text()))
            file.write("%s" %(vdic))
            file.close
            file=0       
            print ret
            print "vdic"
            print vdic
#        self.lerConcentracao()
        return
        

    def lerConcentracao(self):
        f = open('c:elementos')
        elem = []
        linha = f.readline()
        while (len(linha)):
            elem.append(eval(linha))
            linha = f.readline()
        for i in range(len(elem)):
            if elem[i][0] == 221.50:
               print 'achou'
            print elem[i]

    def ler2Concentracao(self):
        fd = QtGui.QFileDialog()
        vfile = fd.getOpenFileName()
#        print vfile  
        if os.path.exists(vfile):
#            print "paasou"
            fileToOpen = open(vfile)
#            initialFile = [string.split(line) for line in fileToOpen]
            initialFile = fileToOpen.read()
            print initialFile
            print type(initialFile)
            vvinitialFile = {}
            vvinitialFile = eval(initialFile)
            print vvinitialFile['txt1']
            return 0
#            print self.slope
#            print self.offset
#            print self.ro
#            print self.kres
        else:
            raise "IOError",("Arquivo não existe %s " % vfile)
            return 1 

    def gravaConcentracao(self):
# teste gravando tabela de elementos para busca
        file=open("c:elementos",'w')
        file.write("%f,'%s',%d,%d\n" %(41.65,'Ce',24,1))
        file.write("%f,'%s',%d,%d\n" %(92.17,'be',4,21))
        file.write("%f,'%s',%d,%d\n" %(273.51,'cc',2,3))
        file.write("%f,'%s',%d,%d\n" %(221.50,'ddd',12,41))
        file.write("%f,'%s',%d,%d\n" %(100.96,'ee',44,51))
        file.close
        file=0       
            
        
    def adicionar(self, pdic):
        n=len(pdic)
        self.nlinhas=n
        print "eeeeeeeeeeeeaaaaqqqquiiiiiiii"
        crtFuncoes.criarGrade(self.ui.tableWidget, n,12,{})
        for i in range(0,n):
            crtFuncoes.incGrade(self.ui.tableWidget,i,pdic[i])

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    appStart = startGui()
    appStart.show()
    sys.exit(app.exec_())
